﻿using System;
using System.Runtime.Remoting.Channels;
using System.Threading;
using Adventure.Server;
using Adventure.Server.Library;
using Adventure.Server.Manager;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Adventure.Tests
{
    /// <summary>
    /// Tests the <see cref="HeartBeatTimer"/>
    /// </summary>
    [TestClass]
    public class HeartBeatTimerTest
    {
        /// <summary>
        /// Heartbeat counter.
        /// </summary>
        private int counter;

        /// <summary>
        /// Tests the Timer of the HeartBeat
        /// </summary>
        [TestMethod]
        public void TestHeartBeatTimer()
        {
            // Create an attributes for AdventureObject
            var attributes = new ObjectAttributes
            {
                [SavedObject.IdentifierAttribute] = "timertest",
                [SavedObject.ClassNameAttribute] = typeof(AdventureObject).AssemblyQualifiedName
            };

            // Create timer and object
            using (var timer = new HeartBeatTimer())
            using (var obj = (AdventureObject) SavedObject.Create(attributes))
            {
                // Set the HeartBeatTimer as default HeartBeatTimer.
                AdventureObject.SetHeartBeatTimer(timer);

                // Register to HeartBeat Event of the object.
                obj.HeartBeat += HeartBeatCall;

                // Set counter to 0
                counter = 0;

                // Activate HeartBeat
                obj.ActivateHeartBeat(HeartBeatReasons.HeartBeat);

                // Wait a little bit so we are not to hard a the limit
                Thread.Sleep((int)(AdventureServerConstants.HeartBeatTime * 1.1));

                for (int i = 0; i < 5; i++)
                {
                    // Check counter
                    Assert.AreEqual(i, counter);

                    // Wait the time of the counter
                    Thread.Sleep(AdventureServerConstants.HeartBeatTime);
                }
            }
        }

        private void HeartBeatCall(object obj, EventArgs e)
        {
            counter++;
        }
    }
}
